package edu.mcw.rgd.clinminer.web;

import com.vaadin.ui.Window;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import edu.mcw.rgd.clinminer.security.Security;

@Configurable
public class ClinminerWindow extends Window {
	private static final Logger log = Logger
			.getLogger(ClinminerApplication.class);

	@Autowired
	private transient Security security;

	private LoginWindow loginWindow;

	@Autowired
	private transient ClinminerApplication application;

	public ClinminerWindow() {
		super("ClinMynEHR");

		loginWindow = new LoginWindow();

		// select window theme
		setTheme("clinminer");

		// Close the application if the main window is closed.
		// to prevent memory leaks
		addListener(new Window.CloseListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void windowClose(CloseEvent e) {
				log.debug(security.getUsername() + " main window closed");
				// getApplication().close();
			}
		});
	}

	@PostConstruct
	public void init() {
		addComponent(application.getCookies());

		if (security.isAuthenticated()) {
			setContent(new ClinminerEntityManagerView());
			removeWindow(loginWindow);
		} else {
			if (!getChildWindows().contains(loginWindow)) {
				addWindow(loginWindow);
			}
		}

	}

}
